package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dtos.AppHttpCodeEnum;
import com.heima.common.dtos.ResponseResult;
import com.heima.common.exception.LeadNewsException;
import com.heima.model.wemedia.dtos.WmLoginDto;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.BCrypt;
import com.heima.utils.common.JwtUtils;
import com.heima.utils.common.RsaUtils;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;

import java.security.PrivateKey;
import java.util.HashMap;

/**
 * <p>
 * 自媒体用户信息表 服务实现类
 * </p>
 *
 * @author QLJ
 * @since 2022-09-02
 */
@Service
@RefreshScope //naocs参数热更新
@Slf4j
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements WmUserService {

    @Value("${leadnews.jwt.privateKeyPath}")
    private String privateKeyPath;    //私钥地址

    @Value("${leadnews.jwt.expire}")
    private int expire;              //token失效时间


    /**
     * 自媒体登录
     */
    @Override
    public ResponseResult wmLogin(WmLoginDto wmLoginDto) {
        //登录用户名号密码
        String name = wmLoginDto.getName();
        String password = wmLoginDto.getPassword();


        //查询条件
        QueryWrapper<WmUser> wrapper = new QueryWrapper<>();
        wrapper.eq("name", name);
        //从数据库查询用户
        WmUser wmUser = getOne(wrapper);

        //判断账号不存在丢处异常
        if (wmUser == null) {
            throw new LeadNewsException(AppHttpCodeEnum.WM_USER_DATA_NOT_EXIST);
        }

        //登录校验密码
        boolean logState = BCrypt.checkpw(password,wmUser.getPassword());
        if (!logState) {
            throw new LeadNewsException(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            //throw new RuntimeException("账号密码错误登陆失败");
        }

        //生成JWT token
        try {
            PrivateKey privateKey = RsaUtils.getPrivateKey(privateKeyPath);
            //将用户密码抹除
            wmUser.setPassword(null);
            String token = JwtUtils.generateTokenExpireInMinutes(wmUser, privateKey, expire);

            HashMap<Object, Object> loginMap = new HashMap<>();
            loginMap.put("token", token);
            loginMap.put("user", wmUser);
            //返回jwt给前端
            return ResponseResult.okResult(loginMap);
        } catch (Exception e) {
            log.info("token生成失败");
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
}
